<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" media="screen" href="/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" media="screen" href="/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" type="text/css" media="screen" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/treetable/jquery.treetable.css"/>
    <link rel="stylesheet" href="/css/treetable/jquery.treetable.theme.default.css"/>
    <script src="/js/libs/jquery-2.1.1.min.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/bootstrap-select.min.css">
    <script src="/js/bootstrap/bootstrap.min.js"></script>
    <script src="/js/bootstrap/bootstrap-select.min.js"></script>
    <script src="/js/jq.js"></script>
    <script src="/js/plugin/bootstrapvalidator/bootstrapValidator.min.js"></script>
    <script src="/js/common.js"></script>
    <script src="/layui/layui.js"></script>
    <script src="/js/dict.js"></script>
    <script src="/js/libs/jquery.ztree.all-3.5.min.js"></script>
    <script src="/js/my/ztree-menu.js"></script>
    <script src="/js/my/permission.js"></script>
    <script src="/js/plugin/datatables/jquery.dataTables.min.js"></script>
    <script src="/js/plugin/datatables/dataTables.bootstrap.min.js"></script>
    <script src="/js/libs/jquery.treetable.js"></script>
</head>
<body>
<div class="col-xs-12 col-sm-12 col-md-11 col-lg-11">
    <form class="form-horizontal" onsubmit="return false" id="form">
        <fieldset>
            <div class='form-group'>
                <label class='col-md-2 control-label'>需求人</label>
                <div class='col-md-4'>
                    <input class='form-control' type='hidden' name='originatorId' id='originatorId'>
                    <input style="width: 90%;float: left;" class='form-control' placeholder='需求人' type='text'
                           name='originatorName' id='originatorName'
                           readonly>
                    <button style="width: 10%;float: right; height: 32px; line-height: 32px;" class="layui-btn layui-btn-sm"
                            onclick="showTableAndFlushFields('user', 'user', '用户', false, false, 'originatorId:id', 'originatorName:nickname', 'originatorOfficeId:deptId', 'originatorOfficeName:deptName')">
                        <i class="layui-icon">&#xe615;</i>
                    </button>
                </div>
                <label class='col-md-2 control-label'>需求部门</label>
                <div class='col-md-4'>
                    <input class='form-control' type='hidden' name='originatorOfficeId' id='originatorOfficeId'>
                    <input style="width: 90%;float: left;" class='form-control' placeholder='需求部门' type='text'
                           name='originatorOfficeName' id='originatorOfficeName' readonly>
                    <button style="width: 10%;float: right; height: 32px; line-height: 32px;"
                            class="layui-btn layui-btn-sm"
                            onclick="showSpecialTree('originatorOfficeId', 'originatorOfficeName', 'dept', '部门', 'root', 'select','fasDeptTree', true, true)">
                        <i class="layui-icon">&#xe615;</i>
                    </button>
                </div>
            </div>
            <div class='form-group'>

            </div>
            <div class='form-group'>
                <label class='col-md-2 control-label'>所在公司</label>
                <div class='col-md-4'>
                    <select class="form-control input-sm selectpicker show-tick" name="companyId" id="companyId"
                            title="所属公司" data-live-search="true"></select>
                </div>
                <label class='col-md-2 control-label'>期望交付时间</label>
                <div class='col-md-4'>
                    <input type="text" class="form-control" placeholder="期望交付时间" name="wishPayDate" id="wishPayDate">
                </div>
            </div>
            <div class='form-group'>

            </div>
            <div class='form-group'>
                <label class='col-md-2 control-label'>总价</label>
                <div class='col-md-4'>
                    <input type="text" class="form-control" placeholder="总价" name="totalPrice" id="totalPrice" readonly>
                </div>
                <!--<label class='col-md-2 control-label'>附件</label>-->
                <!--<div class='col-md-4'>-->
                <!--<input type="hidden" value="">-->
                <!--<ol id="screenshotPathPreview">-->

                <!--</ol>-->
                <!--<button type="button" class="layui-btn" id="screenshotPath">-->
                <!--<i class="layui-icon">&#xe67c;</i>上传文件-->
                <!--</button>-->
                <!--</div>-->
            </div>
            <div class='form-group'>
                <label class='col-md-2 control-label'>附件</label>
                <div class="layui-upload col-md-10">
                    <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" id="selectScreenshotPath">
                        选择多文件
                    </button>
                    <input type="hidden" value="" id="screenshotPath" name="screenshotPath">
                    <button type="button" class="layui-btn layui-btn-sm" id="uploadScreenshotPath">开始上传</button>
                    <div class="layui-upload-list">
                        <table class="layui-table">
                            <thead>
                            <tr>
                                <th>文件名</th>
                                <th>大小</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="screenshotPathList"></tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-2 control-label">备注</label>
                <div class="col-md-10">
                    <textarea class="form-control" placeholder="备注" name="remark" id="remark"></textarea>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-2 control-label">需求明细</label>
                <div class="col-md-10">
                    <button class="layui-btn layui-btn-normal layui-btn-sm" type="button" onclick="addRow()">
                        <i class="fa fa-address-book"></i> 新增行
                    </button>
                    <button class="layui-btn layui-btn-normal layui-btn-sm" type="button" onclick="delRow()">
                        <i class="fa fa-address-book"></i> 删除行
                    </button>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-11 col-md-offset-1">
                    <table id="dt-table" class="table table-striped table-bordered table-hover" style="width: 100%;">
                        <thead>
                        <tr>
                            <th><input id="selectAllRows" type="checkbox"></th>
                            <th style="width: 50px;">行号</th>
                            <th style="width: 150px;">商品</th>
                            <th style="width: 80px;">供应商</th>
                            <th style="width: 80px;">类型</th>
                            <th style="width: 80px;">规格</th>
                            <th style="width: 50px;">单位</th>
                            <th style="width: 80px;">需求数量</th>
                            <th style="width: 100px;">单价</th>
                            <th style="width: 100px;">小计</th>
                            <th style="width: 100px;">待交付数量</th>
                        </tr>
                        </thead>
                        <tbody id="orderDetailList">
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="form-actions">
                <div class="row" align="center">
                    <div class="col-md-12">
                        <button class="btn btn-primary" type="submit" onclick="save()">
                            <i class="fa fa-save"></i> 保存
                        </button>
                    </div>
                </div>
            </div>
        </fieldset>
    </form>
</div>
<script type="text/javascript">
    var pers = checkPermission();

    layui.use(['layer', 'laydate', 'upload'], function () {
        var layer = layui.layer;
        var laydate = layui.laydate;
        var upload = layui.upload;

        laydate.render({
            elem: '#wishPayDate'
        });

        var screenshotPathListView = $('#screenshotPathList');
        var uploadListIns = upload.render({
            elem: '#selectScreenshotPath'
            , url: '/files'
            , accept: 'file'
            , multiple: true
            , auto: false
            , bindAction: '#uploadScreenshotPath'
            , choose: function (obj) {
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function (index, file, result) {
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + file.name + '</td>'
                        , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        // 重新获得所有上传文件
                        $('#screenshotPath').val('');
                        $('.screenshotPathFile').each(function () {
                            $('#screenshotPath').val($('#screenshotPath').val() + '|' + $(this).data('id'));
                        });
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    });

                    screenshotPathListView.append(tr);
                });
            }
            , done: function (res, index, upload) {
                if (res.code === 0) { //上传成功
                    var tr = screenshotPathListView.find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(0).html('<a target="_blank" data-id="' + res.data.id + '" class="screenshotPathFile" href="/files' + res.data.url + '">' + res.data.fileName + '</a>');
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    // tds.eq(3).html(''); //清空操作

                    // 追加文件id
                    $('#screenshotPath').val($('#screenshotPath').val() + '|' + res.data.id);
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
            , error: function (index, upload) {
                var tr = screenshotPathListView.find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
                tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
            }
        });
    });

    $(function () {
        $('#form').bootstrapValidator();
    });

    var companys = showDictSelect('companyId', 'company', '', 'beep');

    var example = $('#dt-table').DataTable({
        "columnDefs": [
            {
                targets: 1,
                width: "100px"
            }
        ],
        "ordering": false,
        // "displayLength" : 10,
        // "scrollY": "calc(100vh - 150px)",
        "scrollX": true,
        "searching": false,
        "processing": true,
        "language": {
            "url": "/js/plugin/datatables/Chinese.lang"
        },
        "dom": "<'dt-toolbar'r>t<'dt-toolbar-footer'<'col-sm-4 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-8' p v>>",
        "createdRow": function (row, data, index) {

        }
    });

    // 根据id查询全部信息，然后赋值给各单元格
    function initDetail(rownum, id) {
        $.ajax({
            type: 'get',
            url: '/goods/' + id,
            success: function (json) {
                if (json.code === 0) {
                    var data = json.data;
                    var row = $('#row_' + rownum).parent();
                    $('#' + rownum + '_detailSpec').val(data.specification);
                    $('#' + rownum + '_detailUnit').val(data.unit);
                    $('#' + rownum + '_detailNum').val(1);
                    $('#' + rownum + '_detailSinprice').val(data.unitPrice);
                    $('#' + rownum + '_detailTotalPrice').val(data.unitPrice);
                    $('#' + rownum + 'waitNum').val(0);
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                var msg = xhr.responseText;
                var response = JSON.parse(msg);
            }

        })

    }

    var rownum = 0;

    function addRow() {
        const elementGoods = rownum + "_goods";
        const elementGoodsId = elementGoods + 'Id';
        const elementGoodsName = elementGoods + 'Name';
        const elementSupplier = rownum + "_supplier";
        const elementSupplierId = elementSupplier + 'Id';
        const elementSupplierName = elementSupplier + 'Name';
        example.row.add([
            "<input id='row_" + rownum + "' name='selectRow' data-detailId='' type='checkbox' >",
            (rownum + 1),
            "<div style='width: 150px;'><input class='form-control' type='hidden' name='orderDetailList[" + rownum + "].goodsId' id='" + elementGoodsId + "'>" +
            "<input style='width: 100px;float: left;'class='form-control' placeholder='商品' " +
            "type='text' name='orderDetailList[" + rownum + "].goodsName' id='" + elementGoodsName + "' readonly>" +
            "<button style='width: 50px;float: right; height: 32px; line-height: 32px;' class='layui-btn layui-btn-sm'" +
            "onclick=\"showTableAndFlushRow('" + elementGoods + "','fas/goods','goods', '商品')\">" +
            "<i class='layui-icon'>&#xe615;</i>" +
            "</button></div>",
            "<div style='width: 150px;'><input class='form-control' type='hidden' name='orderDetailList[" + rownum + "].supplierId' id='" + elementSupplierId + "'>" +
            "<input style='width: 100px;float: left;'class='form-control' placeholder='供应商' " +
            "type='text' name='orderDetailList[" + rownum + "].supplierName' id='" + elementSupplierName + "' readonly>" +
            "<button style='width: 50px;float: right; height: 32px; line-height: 32px;' class='layui-btn layui-btn-sm'" +
            "onclick=\"showTableAndFlushFields('fas/supplier','supplier', '供应商', true, false, '" + elementSupplierId + ":id', '" + elementSupplierName + ":name')\">" +
            "<i class='layui-icon'>&#xe615;</i>" +
            "</button></div>",
            "<select class='form-control input-sm' name='orderDetailList[" + rownum + "].demandType' id='" + rownum + "_demandType' " +
            "title='类型' ></select>",
            "<input class='form-control input-sm' id='" + rownum + "_detailSpec' name='orderDetailList[" + rownum + "].detailSpec' readonly>",
            "<input class='form-control input-sm' id='" + rownum + "_detailUnit' name='orderDetailList[" + rownum + "].detailUnit' readonly>",
            "<input class='form-control input-sm' id='" + rownum + "_detailNum' name='orderDetailList[" + rownum + "].detailNum'>",
            "<input class='form-control' id='" + rownum + "_detailSinprice' name='orderDetailList[" + rownum + "].detailSinprice'>",
            "<input class='form-control' id='" + rownum + "_detailTotalPrice' name='orderDetailList[" + rownum + "].detailTotalPrice' readonly>",
            "<input class='form-control' id='" + rownum + "_waitNum' name='orderDetailList[" + rownum + "].waitNum' readonly>"
        ]).draw();
        showDictSelect(rownum + '_companyId', 'company', '', 'beep');
        showDictSelect(rownum + '_demandType', 'demand_Type', '', '10');

        //给第一个单元格的checkbox绑定点击事件
        $('#row_' + rownum).bind('click', function () {
            var $row = $(this).parent().parent();
            if ($row.hasClass('success')) {
                $row.removeClass('success');
            } else {
                $row.addClass('success');
            }
        });

        // 给数量和单价绑定计算小计事件
        $('#' + rownum + '_detailNum, #' + rownum + '_detailSinprice').on('input propertychange', function () {
            calcDetailTotalPrice(this);
        });

        rownum++;
    }

    addRow();

    function delRow() {
        example.rows('.success').remove().draw(false);
        calcTotalPrice();
    }

    // 计算行内小计价格
    function calcDetailTotalPrice(obj) {
        var tr = $(obj).parents('tr').eq(0);
        var goodsId = tr.find('input[id$=goodsId]').eq(0).val();
        var goodsName = tr.find('input[id$=goodsName]').eq(0).val();
        if (!goodsId || !goodsName) {
            $(obj).val(0);
            layer.msg("请先选择商品");
            return;
        }

        var id = $(obj).attr('id');
        var rowNum = id.split('_')[0];

        var detailNum = $('#' + rowNum + '_detailNum').val();	//明细数量
        if (isNaN(detailNum) || parseFloat(detailNum) < 0) {
            $('#' + rowNum + '_detailNum').val(1);
            layer.msg("需求数量必须为正数");
            return;
        }
        detailNum = parseFloat(detailNum);

        var detailSinprice = $('#' + rowNum + '_detailSinprice').val();	//明细单价
        if (isNaN(detailSinprice) || parseFloat(detailSinprice) < 0) {
            $('#' + rowNum + '_detailSinprice').val(0.0);
            layer.msg("单价必须为正数");
            return;
        }
        detailSinprice = parseFloat(detailSinprice);

        var detailTotalPrice = detailSinprice * detailNum;
        $('#' + rowNum + '_detailTotalPrice').val(detailTotalPrice);	//明细小计
        calcTotalPrice();
    }

    // 计算主单总价格
    function calcTotalPrice() {
        var amount = 0.0; //采购总额
        $('#orderDetailList').find('input[id$=_detailTotalPrice]').each(function () {
            var detailTotalPrice = $(this).val();
            amount += isNaN(detailTotalPrice) ? 0 : parseFloat(detailTotalPrice);
        });
        $('#totalPrice').val(amount);
    }

    function save() {
        $('#form').bootstrapValidator();
        var bootstrapValidator = $("#form").data('bootstrapValidator');
        bootstrapValidator.validate();
        if (!bootstrapValidator.isValid()) {
            return;
        }

        var formdata = $("#form").serializeObject();

        $.ajax({
            type: 'post',
            url: '/order/',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(formdata),
            success: function (data) {
                if (data.code === 0) {
                    layer.msg("保存成功", {shift: -1, time: 1000}, function () {
                        // location.href = "orderList.html";
                        deleteCurrentTab();
                        $('#menu a[data-url="pages/fas/order/orderList.html"]').click();
                    });
                } else {
                    layer.msg("保存失败：" + data.message, {shift: -1, time: 1000});
                }
            }
        });
    }

</script>
</body>
</html>
